import pymongo
import common.gyblog as log
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

LOG = log.get_logger()
SERVICE = ChromeService(executable_path="../common/chromedriver.exe")
CONNECTION_STR = 'mongodb://192.168.0.196:27017/?readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false'
# CONNECTION_STR = 'mongodb://192.168.0.196:27017/'
DATA_BASE = 'movies_record'
DB_COL = 'javbook'
SERIES = 'Caribbeancompr'
NAMES = ['121622_001', '120922_005', '121622_006', '111122_001', '110522_001', '111122_006', '110322_001', '101422_001',
         '100822_001', '101222_001', '100722_001', '100522_001', '100122_001', '100722_007', '092522_001', '083022_001',
         '090222_001', '081822_001', '081622_001', '082522_001', '081222_001', '081922_003', '081522_001', '080522_001',
         '081222_002', '080422_002', '080222_001', '080322_001', '073022_001', '082622_001', '072322_001', '072222_001',
         '072022_001', '071522_001', '072622_001', '071622_001', '070522_001', '063022_001', '070222_001', '070922_001',
         '062422_001', '062122_001', '062522_001', '060822_001', '062222_001', '060922_001', '062922-001', '031122_003',
         '010722_003']


def seek_tor_by_names(name):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]
    # 查询
    query = {'num': name}
    projection = {'_id': 0, 'detail_url': 1}
    ans = list(db_col.find(query, projection))
    # 关闭数据库连接
    db_client.close()
    # 结果处理
    if len(ans) == 1:
        detail_url = ans[0]['detail_url']
        print('数据库中已搜索到：{}，{}'.format(name, detail_url))
        LOG.info('数据库中已搜索到：{}，{}'.format(name, detail_url))
        return detail_url
    else:
        print('没有搜到：{}'.format(name))
        LOG.info('没有搜到：{}'.format(name))
        return 'None'


def save_tor(url):
    # 创建 WebDriver 对象
    driver = webdriver.Chrome(service=SERVICE)
    driver.get(url)
    elements = driver.find_elements(By.XPATH, '/html/body/div[7]/div[position()]/span/a')

    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    # 遍历元素并获取 href 属性
    ans = []
    for element in elements:
        name = element.text
        ratio = element.text.split('-')[-1]
        if '[ThZu.Cc]' in name and ratio == '1080p':
            tor = element.get_attribute('href')
            ans.append(tor)
        if '[Thz.la]' in name and ratio == '1080p':
            tor = element.get_attribute('href')
            ans.append(tor)
        if '[psk.la]' in name and ratio == 'FHD':
            tor = element.get_attribute('href')
            ans.append(tor)
        if '3xplanet' in name:
            tor = element.get_attribute('href')
            ans.append(tor)
        if '[UNCENSORED]' in name:
            tor = element.get_attribute('href')
            ans.append(tor)
        if '[JAV][Uncensored]' in name and '[1080p]' in name:
            tor = element.get_attribute('href')
            ans.append(tor)
        if '会飞的象' in name:
            tor = element.get_attribute('href')
            ans.append(tor)
    if len(ans) == 0:
        print('{}：没有找到tor'.format(url))
        LOG.info('{}：没有找到tor'.format(url))
    else:
        query = {'detail_url': url}
        new_values = {"$set": {"tor": ans[0]}}
        db_col.update_one(query, new_values)
        print('已插入tor in {}'.format(url))
        LOG.info('已插入tor in {}'.format(url))
    driver.close()
    db_client.close()


def query_tor_by_names(names):
    # 连接数据库
    db_client = pymongo.MongoClient(CONNECTION_STR)
    db_database = db_client[DATA_BASE]
    db_col = db_database[DB_COL]

    ans = []
    error_ans = []

    for name in names:
        # 查询
        query = {'num': name}
        projection = {'_id': 0, 'tor': 1}
        query_ans = list(db_col.find(query, projection))
        if query_ans[0]['tor'] == '':
            error_ans.append(name)
        else:
            ans.append(query_ans[0]['tor'])
    print('搜索到的磁力：')
    for a in ans:
        if a != '':
            print(a)
    print('未搜索到的番号：')
    for e in error_ans:
        print(e)
    print('共{}个，{}有tor,{}没有'.format(len(names), len(ans), len(error_ans)))
    db_client.close()


if __name__ == '__main__':
    # for name in NAMES:
    #     detail_url = seek_tor_by_names(name)
    #     if detail_url != 'None':
    #         save_tor(detail_url)
    query_tor_by_names(NAMES)
